package com.atdyc.schedule.controller;

import com.atdyc.schedule.pojo.SysUser;
import com.atdyc.schedule.service.SysUserService;
import com.atdyc.schedule.service.impl.SysUserServiceImpl;
import com.atdyc.schedule.util.MD5Util;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/user/*")
public class SysUserController extends BaseController {
    //创建服务层对象
    private SysUserService userService = new SysUserServiceImpl();

    /**
     * 接收用户登录请求，完成登录业务接口
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收用户名和密码
        String username = req.getParameter("username");
        String userPwd = req.getParameter("userPwd");
        //调用服务层，根据用户名查询信息
        SysUser loginUser = userService.findByUaername(username);
        if (loginUser == null) {
            resp.sendRedirect( "/loginUsernameError.html");
        }else if (!MD5Util.encrypt(userPwd).equals(loginUser.getUserPwd())){
            //判读密码
            resp.sendRedirect( "/loginUserPwdError.html");
        }else{
            //4 跳转到首页
            resp.sendRedirect("/showSchedule.html");
        }

    }

    /**
     * 接收用户注册请求的业务处理方法(业务接口)
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1 接收客户端提交的参数
        String username = request.getParameter("username");
        String userPwd = request.getParameter("userPwd");
        // 2 调用服务层方法,完成注册功能
        //将参数放入一个SysUser对象中,在调用regist方法时传入
        SysUser sysUser = new SysUser(null, username, userPwd);
        int rows = userService.regist(sysUser);
        // 3 根据注册结果(成功  失败) 做页面跳转
        if (rows > 0) {
            response.sendRedirect("/registSuccess.html");
        } else {
            response.sendRedirect("/registFail.html");
        }
    }

}
